<?php

include("Config.php");




function FormValidate($tablename,$ValideTemplate)
{
  
   $Validate="";

    $result= mysql_query("show full fields from $tablename");
    if (!$result) 
    {
    echo 'Could not run query: ' . mysql_error();
    exit;
   }
    if (mysql_num_rows($result) > 0)
     {

        while ($row = mysql_fetch_assoc($result)) 
        {
           if($row["Null"]=="NO")
           {
              if($row["Key"]=="PRI")
              {
               $Validate.="array('".$row['Field']."','require','{$row['Field']}主健冲突',1,'unique',1),\n\t\t"; 
              }
              else
              {
               if(($row["Comment"]=="")||($row["Comment"]==null))
               { 
                  $Validate.="array('".$row['Field']."','require','{$row['Field']}不能为空',1),\n\t\t";
               }
               else
               {
                 $Validate.="array('".$row['Field']."','require','{$row['Comment']}不能为空',1),\n\t\t";  
               }
              } 
           }
           else
           {
             $Validate.="//array('".$row['Field']."','require','{$row['Field']}不能为空',1),\n\t\t";   
           }               
        }
              
    

    }
   
   return TemplateReplace("Validate",$Validate,$ValideTemplate);
}





function FieldType($colum)
{
     $fieldtypes= preg_split("/\s/",preg_replace("/\([\s\S].*\)/","",  $colum["Type"]));
     if(count($fieldtypes)>0)
     $fieldtype=$fieldtypes[0];
     else
      $fieldtype=$fieldtypes;
     return $fieldtype; 
}

function FieldLen($colum)
{
      preg_match("/\([(\d*)]\)/",$colum["Type"],$result);
      if(count($result)>0)
      {
          return $result[1];
      }
      else
      {
          return 0;
      }
}

function FieldsInfo($tablename)
{
       $result= mysql_query("show full fields from $tablename");
    if (!$result) 
    {
    echo 'Could not run query: ' . mysql_error();
    exit;
   }
   $res=array();
    if (mysql_num_rows($result) > 0)
     {
        $i=0;
        while ($row = mysql_fetch_assoc($result)) 
        {
               // print_r($row);
             // $fieldlist.=EditListColum($row); 
             $res[$i]=$row;
             $i=$i+1;
               
        }

    }
    
    return $res;
}


function FieldMap($tablname)
{ 
   $map="";
   $fields= FieldsInfo($tablname);
     for($i=0;$i<=count($fields)-1;$i++){
       $map.="//'".$fields[$i]["Field"]."'=>'".$fields[$i]["Field"]."',\n\t";     
     } 
   return $map; 
}


function ModelInsertSql($tablname)
{ 
   $map=array();
   $fields= FieldsInfo($tablname);
     for($i=0;$i<=count($fields)-1;$i++){
       $map['FieldsName'].="{$fields[$i]["Field"]},"; 
       if((i%2)==0) 
       $map["FieldsValue"].="'{\$P['{$fields[$i]["Field"]}']}',\n\t\t\t";    
     }     
   if( substr($map['FieldsName'],strlen($map['FieldsName'])-1,1)==",")
    $map['FieldsName']=substr($map['FieldsName'],0,strlen($map['FieldsName'])-1); 
     if( substr($map['FieldsValue'],strlen($map['FieldsValue'])-5,5)==",\n\t\t\t")
    $map['FieldsValue']=substr($map['FieldsValue'],0,strlen($map['FieldsValue'])-5);
      
   return $map; 
}


function ModelUpdateSql($tablname)
{ 
  // $map=array();
   $fields= FieldsInfo($tablname);
     for($i=0;$i<=count($fields)-1;$i++){
       $map.=$fields[$i]["Field"]."="."'{\$P['{$fields[$i]["Field"]}']}',\n\t\t\t"; 
     }     
   if( substr($map,strlen($map)-5,5)==",\n\t\t\t")
    $map=substr($map,0,strlen($map)-5);    
   return $map."\n\t\t\t"; 
}


function FieldColModel($tablename)
{
    
     $fields= FieldsInfo($tablename);
    $map="";
     for($i=0;$i<=count($fields)-1;$i++){
     if(($fields[$i]["Comment"]=="")||($fields[$i]["Comment"]==null))    
     $map.="{display: '".$fields[$i]["Field"]."', name : '".$fields[$i]["Field"]."', width : 40, sortable : true, align: 'left'},";
     else
     $map.="{display: '".$fields[$i]["Comment"]."', name : '".$fields[$i]["Field"]."', width : 40, sortable : true, align: 'left'},";    
     }
     
      
   return substr($map,0,strlen($map)-1); 
    
}

function FieldSearchItems($tablename)
{
    
    $fields= FieldsInfo($tablename);
    $map="";
     for($i=0;$i<=count($fields)-1;$i++){
     if(($fields[$i]["Comment"]=="")||($fields[$i]["Comment"]==null))    
     $map.="{display: '".$fields[$i]['Field']."', name : '".$fields[$i]['Field']."'},";
     else
     $map.="{display: '".$fields[$i]['Comment']."', name : '".$fields[$i]['Field']."'},";    
     }
     
      return substr($map,0,strlen($map)-1);  
    
}




function FormAuto($tablename,$FormAutoTemplate)
{
  
   $Auto="";
    $result= mysql_query("show full fields from $tablename");
    if (!$result) 
    {
    echo 'Could not run query: ' . mysql_error();
    exit;
   }
    if (mysql_num_rows($result) > 0)
     {

        while ($row = mysql_fetch_assoc($result)) 
        {
           if(($row["Default"]!="")||($row["Default"]!=null))
           {  
               
              $Auto.="array('".$row['Field']."','{$row['Default']}',1),\n\t\t"; 
           }
           else
           {
               if(FieldType($row)=="tinyint")
               $Auto.="//array('".$row['Field']."',0,1),\n\t\t";
               else if(FieldType($row)=="date")
               $Auto.="//array('".$row['Field']."','date',1,'function'),\n\t\t";
               else if(FieldType($row)=="datetime")
               $Auto.="//array('".$row['Field']."','time',1,'function'),\n\t\t";
               else 
              $Auto.="//array('".$row['Field']."','{$row['Default']}',1),\n\t\t";   
           }               
        }

    }
   
   return TemplateReplace("Auto",$Auto,$FormAutoTemplate);
}

function createDir($path)
{
    $dir='';
    $path = split('[/]', $path);
    if(is_array($path))
    {
        foreach($path as $v)
        {
            $dir .= $v;
            if(!file_exists($dir))
                mkdir($dir,0700);
            $dir .= '/';
        }
    }
}



createDir($ActionPath);
createDir($ModelPath);
createDir($ViewBasePath);


function ReplaceTableName($tablename,$DbPrefix)
{
    $tablename= strtolower( preg_replace('/^'.$DbPrefix.'/',"",$tablename));
    $tablenames= preg_split("/_/",$tablename);
    $trueTableName="";
     foreach ($tablenames as $value) {
      $trueTableName.=strtoupper(substr( $value,0,1)).substr( $value,1,strlen($value)-1);
     }
    return $trueTableName;
}



function TemplateReplace($key,$value,$subject)
{
  return   preg_replace("/\{".$key."\}/i",$value,$subject);
}


function WriteFile($filename,$content)
{
    $filename=$filename;
    $f=fopen($filename,"w");
    fwrite($f,$content);
    fclose($f);
    
}


$ModelTemplate=<<<eot
<?php
class {Form}Model extends CommonModel {

   //模型数据库   
   //protected \$dbName = '{DataBaseName}';


  //模型对表数据表的真实名称
  // protected \$trueTableName = '{TableName}'; 

   {Map}
   {Validate}
   {Auto}
   {ModelInserSql}
   {ModelUpdateSql}
   
           //自定义查询
        /*
        function buildWhere(\$P)
        {
           \$w="";
           \$qtypes=preg_split("/,/",\$P["qtype"]);
           \$querys= preg_split("/,/",\$P["query"]);
           for(\$i=0;\$i<count(\$qtypes);\$i++){
             \$w.="{\$qtypes[\$i]} like '%{\$querys[\$i]}%' and "; 
           }
           if(substr(\$w,strlen(\$w)-4,4)=="and ")
           \$w=substr(\$w,0,strlen(\$w)-4); 
           //print_r(\$w);
           return \$w;
            
        }
        */
        //生成json数据
        /*
        public function  json(\$action,\$P,\$primaryKey)
        {
            
           \$sql="";
           return parent::json(\$action,\$sql,\$P,\$primaryKey);  
            
        }
        */

}

/*
class {Form}Model extends Model {


}
*/
?>
eot;


$ActionTemplate=<<<eot
<?php

class {Form}Action extends CommonAction {

     //建立自定义查询   
     /*
      function buildWhere()
      {
         return "";
      }
     */
     //操作初始化
     /*
     public function __construct() 
     {
         C("DB_PREFIX","");
         parent::__construct();
     }
     */
     //自定义FlexGrid显示,多用于关联查询
     /*
     public function json()
     {
         \$f=D('{Form}');
         //json 第一个为Action对象,第二个传过来的对象,第三个为主健
         //如果Action为null,则返回json数据,用buildJSON进行封装
         \$result= \$f->json(\$this,\$this->paras,"id");

     }
     */
     //数据效验
     function validate(&\$err="")
     {
         \${Form} = D("{Form}"); 
        \$result = \${Form}->create();
        if (!\$result){
          \$err= \${Form}->getError();
          //\$this->error(\$err);
           return false;
        }else{
          return true;                                
        }

     }
    
      //数据插入
      public function insert()
     {
         \${Form}=D('{Form}');
        if(\$this->validate(\$err))
        { 
            if( \${Form}->insertBySql(\$this->paras))
            {
                 \$this->success("插入成功");
            }
            else
            {
                \$this->error("插入失败,请检查数据");
            }
        }
        else
        {
             \$this->error(\$err);
        }
     } 
     //数据更新
      public function update()
     {
        \${Form}=D('{Form}');
        if(\$this->validate(\$err))
        { 
            if( \${Form}->updateBySql(\$this->paras))
            {
                 \$this->success("更新成功");
            }
            else
            {
                \$this->error("没有更新数据");
            }
        }
        else
        {
             \$this->error(\$err);
        }

     }   

}


/*
class {Form}Action extends Action{

    // 查询数据
    public function show{Form}(){
        \$Form    = M("{Form}");
        import("@.ORG.Page"); //导入分页类
        \$count = \$Form->count();    //计算总数
        \$p = new Page ( \$count, 5 );
       // \$list    =    \$Form->limit(5)->order('id desc')->findAll();
       \$list=\$Form->limit(\$p->firstRow.','.\$p->listRows)->order('id desc')->findAll();
        \$this->assign('list',\$list);
        \$page = \$p->show (); 
        \$this->assign('page',\$page);
        \$this->display();
    }
    // 写入数据
    public function insert{Form}() {
        \$Form    =    D("{Form}");
        if(\$vo = \$Form->create()) {
            \$list=\$Form->add();
            if(\$list!==false){
                \$this->success('数据保存成功！');
            }else{
                \$this->error('数据写入错误！');
            }
        }else{
            \$this->error(\$Form->getError());
        }
    }

    // 更新数据
    public function update{Form}() {
        \$Form    =    D("{Form}");
        if(\$vo = \$Form->create()) {
            \$list=\$Form->save();
            if(\$list!==false){
                \$this->success('数据更新成功！');
            }else{
                \$this->error("没有更新任何数据!");
            }
        }else{
            \$this->error(\$Form->getError());
        }
    }
    // 删除数据
    public function delete{Form}() {
        if(!empty(\$_POST['id'])) {
            \$Form    =    M("{Form}");
            \$result    =    \$Form->delete(\$_POST['id']);
            if(false !== \$result) {
                \$this->ajaxReturn(\$_POST['id'],'删除成功！',1);
            }else{
                \$this->error('删除出错！');
            }
        }else{
            \$this->error('删除项不存在！');
        }
    }

    // 编辑数据
    public function edit{Form}() {
        if(!empty(\$_GET['id'])) {
            \$Form    =    M("{Form}");
            \$vo    =    \$Form->getById(\$_GET['id']);
            if(\$vo) {
                \$this->assign('vo',\$vo);
                \$this->display();
            }else{
                exit('编辑项不存在！');
            }
        }else{
            exit('编辑项不存在！');
        }
    }

}

*/


?>
eot;


$DeleteTemplate=<<<eot
 <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html>
<head>
<title>页面提示</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv='Refresh' content='{\$waitSecond};URL={\$jumpUrl}'>
<load href ="__PUBLIC__/css/style.css" />

<script>
        function back()
        {
            if(self.parent)
            {
              self.parent.tb_remove();
              self.parent.flexReload();
            }
            else
            { 
              window.setTimeout(function (){window.location.href='__URL__/index',20000});
            }
        }
</script>

</head>
<body>
<div class="message" style="margin:1%;width:400px">
<table class="message"  cellpadding=0 cellspacing=0 >
    <tr>
        <td height='5'  class="topTd" ></td>
    </tr>
    <tr class="row" >
        <th class="tCenter space">{\$msgTitle}</th>
    </tr>
    <present name="message" >
    <tr class="row">
        <td style="color:blue">{\$message}</td>
    </tr>
    </present>
    <present name="error" >
    <tr class="row">
        <td style="color:red">{\$error}</td>
    </tr>
    </present>
    <present name="closeWin" >
        <tr class="row">
        <td>系统将在 <span style="color:blue;font-weight:bold">{\$waitSecond}</span> 秒后自动关闭，如果不想等待,直接点击 <a href="{\$jumpUrl}">这里</a> 关闭</td>
    </tr>
    </present>
    <notpresent name="closeWin" >
    <tr class="row">
        <td> <span style="color:blue;font-weight:bold">{\$waitSecond}</span> <a onclick="back()" href="#">返回</a></td>
    </tr>
    </notpresent>
    <tr>
        <td height='5' class="bottomTd"></td>
    </tr>
    </table>
</div>
</body>
</html>


eot;


$AddTemplate=<<<eot
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>ThinkPHP示例：CURD操作</title>
<load href='__PUBLIC__/Css/common.css' />
<load href="__PUBLIC__/Js/Base.js" />
<load href="__PUBLIC__/Js/prototype.js" />
<load href="__PUBLIC__/Js/mootools.js" />
<load href="__PUBLIC__/Js/Ajax/ThinkAjax.js" />
<load href="__PUBLIC__/Js/editor/kindeditor.js" />

 </head>
 <body><script language="JavaScript">
 <!--
    function add(){
        ThinkAjax.sendForm('form1','__URL__/insert',complete,'result');
    }
    function complete(data,status){
        if (status==1)
        {
             if(self.parent)
             {
             window.setTimeout(function (){window.location.href='__URL__/index',20000});
             self.parent.tb_remove();
             self.parent.flexReload();
             }

        }
    }
    
    // KE.show({ 
        //id : 'id' //TEXTAREA输入框的ID 
  // });

    
 //-->
 </script>
 <div class="main">
 <h2>ThinkPHP示例之：CURD操作 [ 新增数据表单 ] </h2>
    <form id="form1" method='post' action="__URL__/insert">
 <table cellpadding=2 align="center" cellspacing=2>
   <tr>
    <td colspan="2"><div id="result" class="none result" style="font-family:微软雅黑,Tahoma;letter-spacing:2px"></div></td>
 </tr>
  {FormList}
 <tr>
    <td><input type="hidden" name="ajax" value="1"></td>
    <td><input type="button" onClick="add()" class="button" value="保 存"> <input type="reset" class="button" value="清 空"></td>
 </tr>
 </table>
   </form>
</div>
 </body>
</html>


eot;



$EditTemplate=<<<eot

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>ThinkPHP示例：CURD操作</title>
<load href='__PUBLIC__/Css/common.css' />
<load href='__PUBLIC__/Css/sytle.css' />  
<load href="__PUBLIC__/Js/Base.js" />
<load href="__PUBLIC__/Js/prototype.js" />
<load href="__PUBLIC__/Js/mootools.js" />
<load href="__PUBLIC__/Js/Ajax/ThinkAjax.js" />
 </head>
 <body><script language="JavaScript">
 <!--
    function save(){
        ThinkAjax.sendForm('form1','__URL__/update',complete,'result');
    }
    function complete(data,status){
        if (status==1)
        {
            if(self.parent)
            { 
              window.setTimeout(function (){window.location.href='__URL__/index',20000});
              self.parent.tb_remove();
              self.parent.flexReload();
            }
     
     
      
        
        }
    }
    
        // KE.show({ 
        //id : 'id' //TEXTAREA输入框的ID 
         // });
 //-->
 </script>
 <div class="main">
 <h2>ThinkPHP示例之：CURD操作</h2>
 编辑数据表单
   <form id="form1" method='post' action="">
 <table cellpadding=2 align="center" cellspacing=2>
  <tr>
    <td colspan="2"><div id="result" class="none result" style="font-family:微软雅黑,Tahoma;letter-spacing:2px"></div></td>
 </tr>
 {EditList}
 <tr>
    <td><input type="hidden" name="ajax" value="1"><input type="hidden" name="id" value="{\$vo.id}"></td>
    <td><input type="button" onClick="save()" class="button" value="保 存"> <input type="reset" class="button" value="清 空"></td>
 </tr>
 </table>
   </form>
</div>
 </body>
</html>

eot;


$ListTemplate=<<<eot

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>ThinkPHP示例：CURD操作</title>
<load href='__PUBLIC__/Css/common.css' />
<load href="__PUBLIC__/Js/Base.js" />
<load href="__PUBLIC__/Js/prototype.js" />
<load href="__PUBLIC__/Js/mootools.js" />
<load href="__PUBLIC__/Js/Ajax/ThinkAjax.js" />
 </head>
 <body><script language="JavaScript">
 <!--
    function add(){
        window.location.href="__URL__/add";
    }
    function edit(id){
        window.location.href="__URL__/edit/id/"+id;
    }
    function del(id){
        ThinkAjax.send('__URL__/delete','ajax=1&id='+id,complete,'result');
    }
    function complete(data,status){
        if (status==1)
        {
            $('div_'+data).outerHTML = '';
        }
    }
    function sortBy (field){
     alert(window.location.search);
     location.href = "?_order="+field+"&_sort=";

    }

    
 //-->
 </script>
 <div class="main">
 <h2>ThinkPHP示例之：CURD操作</h2>
方便地完成对单表的CURD操作<P>
 <div id="list" > 
 <table border=1 cellpadding=2 cellspacing=2>
  <tr>
    <td colspan="20"><input type="button" value="新 增" class="small button" onClick="add()"><div id="result" class="none result" style="font-family:微软雅黑,Tahoma;letter-spacing:2px"></div></td>
 </tr>
 <tr><td colspan="20">  {\$page}</td>  </tr>
  <tr>
 
 
    {Header}
    <volist name="list" id="vo">
     {ListResult}
    </volist> 
    </td>
  </tr>
   
 <tr><td colspan="20">  {\$page}</td>  </tr>  
 </table>
 

</div>
 </body>
</html>

eot;


$CommonActionTemplate=<<<eot
<?php
class CommonAction extends Action {
   //传递参数 
    protected \$paras=array();

    // 查询数据
    public function index(){
        
        
      \$name=  \$this->getActionName();
        \$Form    = M(\$name);
        import("@.ORG.Page"); //导入分页类
        \$count = \$Form->count();    //计算总数
        \$p = new Page ( \$count, 5 );
       // \$list    =    \$Form->limit(5)->order('id desc')->findAll();
       \$list=\$Form->limit(\$p->firstRow.','.\$p->listRows)->order('id desc')->findAll();
        \$this->assign('list',\$list);
        \$page = \$p->show (); 
        \$this->assign('page',\$page);
        \$this->display();
    }

      //数据写入
      function insert() {
        //B('FilterString');
        \$name=\$this->getActionName();
        \$model = D (\$name);
        if (false === \$model->create ()) {
            \$this->error ( \$model->getError () );
        }
        //保存当前数据对象
        \$list=\$model->add ();
        if (\$list!==false) { //保存成功
            \$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
            \$this->success ('新增成功!');
        } else {
            //失败提示
            \$this->error ('新增失败!');
        }
    }
    //数据编辑
    function edit() {
        \$name=\$this->getActionName();
        \$model = M ( \$name );
        \$id = \$_REQUEST [\$model->getPk ()];
        \$vo = \$model->getById ( \$id );
        \$this->assign ( 'vo', \$vo );
        \$this->display ();
    }
    //数据更新
    function update() {
        //B('FilterString');
        \$name=\$this->getActionName();
        \$model = D ( \$name );
        if (false === \$model->create ()) {
            \$this->error ( \$model->getError () );
        }
        // 更新数据
        \$list=\$model->save ();
        if (false !== \$list) {
            //成功提示
            \$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
            \$this->success ('编辑成功!');
        } else {
            //错误提示
            \$this->error ('编辑失败!');
        }
    }
    //数据删除
    public function delete() {
        //删除指定记录
        \$name=\$this->getActionName();
        \$model = M (\$name);
        if (! empty ( \$model )) {
            \$pk = \$model->getPk ();
            \$id = \$_REQUEST [\$pk];
            if (isset ( \$id )) {
                \$condition = array (\$pk => array ('in', explode ( ',', \$id ) ) );
                \$list=\$model->where ( \$condition )->delete();
                if (\$list!==false) {
                    \$this->success ('删除成功！' );
                } else {
                    \$this->error ('删除失败！');
                }
            } else {
                \$this->error ( '非法操作' );
            }
        }
    }   
    //生成多查询条件
    function buildWhere()
    {
       \$w="";
       \$qtypes=preg_split("/,/",\$this->P("qtype"));
       \$querys= preg_split("/,/",\$this->P("query"));
       for(\$i=0;\$i<count(\$qtypes);\$i++){
         \$w.="{\$qtypes[\$i]} like '%{\$querys[\$i]}%' and "; 
       }
       if(substr(\$w,strlen(\$w)-4,4)=="and ")
       \$w=substr(\$w,0,strlen(\$w)-4); 
       //print_r(\$w);
       return \$w;
        
    }
    
    //生成FlexGrid数据
    public function buildJSON(\$data,\$primaryKey,\$page,\$total)
    {
        
        header("Content-type:text/html;charset=utf-8");   //这句很重要,防止乱码  
        \$json = "";
        \$json .= "{";
        \$json .= "page: \$page,";
        if(\$total)
        \$json .= "total: \$total,";
        else
        \$json .= "total: 0,"; 
        \$json .= "rows: [";
        \$rc = false;
        \$j=count(\$data)-1;
        // \$pk=\$Form->getPk()?\$Form->getPk():\$Form->pk;
        \$pk=\$primaryKey?\$primaryKey:"id";
        for(\$i=0;\$i<=\$j;\$i++)
        {
           // \$json .= ",";
            \$json .= "{";
            \$json .= "id:'".\$data[\$i][\$pk]."',"; 
            \$json .= "cell:[";              
            foreach (\$data[\$i] as \$key => \$value) {
            \$json .= "'".addslashes(\$value)."',";
            }
            if(substr(\$json,strlen(\$json)-1,1)==",")
            \$json=substr(\$json,0,strlen(\$json)-1);
            \$json .="]"."},";  
        
        }
        if(\$j>=0)  //这句也很重要
        \$json=substr(\$json,0,strlen(\$json)-1);
        \$json .= "]";
        \$json .= "}";
        return \$json;
        
    }
    
    
    
    //生成json数据
    public function  json()
    {
        
        /*
        \$page = \$_POST['page'];
        \$rp = \$_POST['rp'];
        \$sortname = \$_POST['sortname'];
        \$sortorder = \$_POST['sortorder'];  
        \$qtype=\$_POST["qtype"]; 
        \$query=\$_POST["query"];
        */
        
        \$page=\$this->P('page');
        \$rp=\$this->P('rp');
        \$sortname=\$this->P('sortname');
        \$sortorder=\$this->P('sortorder');
        \$qtype=\$this->P('qtype');
        \$query=\$this->P('query');
        
        if(!\$sortorder) \$sortorder="asc";
        
        if(!\$sortname) \$sortname="id"; 
        
        if(!\$page) \$page=1;  
        
        if(!\$rp ) \$rp =10; 
        
         
        
         \$name=  \$this->getActionName();
        \$Form    = M(\$name); 
        if (method_exists ( \$this, '_filter' )) {
            \$this->_filter ( \$map );
            \$list=\$Form->where(\$map)->limit((\$page-1)*\$rp.','.\$rp)->order("\$sortname \$sortorder")->findAll(); 
           \$total=\$Form->where(\$map)->count();
             
        }
        else 
        if(\$query&&\$qtype)
        {
            
           \$list=\$Form->where(\$this->buildWhere())->limit((\$page-1)*\$rp.','.\$rp)->order("\$sortname \$sortorder")->findAll(); 
           //\$list=\$Form->where("\$qtype like '%{\$query}%'")->limit((\$page-1)*\$rp.','.\$rp)->order("\$sortname \$sortorder")->findAll(); 
           \$total=\$Form->where(\$this->buildWhere())->count();
          // \$total=\$Form->where("\$qtype like '%{\$query}%'")->count();
        }
        else
        {
        
        \$total=\$Form->count();
        \$list=\$Form->limit((\$page-1)*\$rp.','.\$rp)->order("\$sortname \$sortorder")->findAll();
        }

          header("Content-type:text/html;charset=utf-8");   //这句很重要,防止乱码  
       echo \$this->buildJSON(\$list,\$Form->pk,\$page,\$total); 
        
    }
    
      //flexgrid视图
        function view()
    {
       \$this->display();
    }
    
     //初始化操作
     
       public function __construct()
       {
           \$this->initParas(); 
           parent::__construct();
          
       }    
    
    

    //初始化参数
    
    function initParas()
    {
       
   
       if(count(\$_POST)>0) 
        foreach (\$_POST as \$key => \$value) {
            
            \$this->paras[strtolower(\$key)]=addslashes(\$value);
        
        }
        
        if(count(\$_GET)>0) 
        foreach (\$_GET as \$key => \$value) {
            
            \$this->paras[strtolower(\$key)]=addslashes(\$value);
            
        }
    }
    
    //取得参数
    
    public function P(\$paraName)
    {
        return \$this->paras[\$paraName];
    }
    
 
 
}
?>




eot;

$CommonModelTemplate=<<<eot
<?php
class CommonModel extends Model {
       //替换操作
       function TemplateReplace(\$key,\$value,\$subject)
        {
          return   preg_replace("/\{".\$key."\}/i",\$value,\$subject);
        } 
      //生成查询  
      function buildWhere(\$P)
        {
           \$w="";
           \$qtypes=preg_split("/,/",\$P["qtype"]);
           \$querys= preg_split("/,/",\$P["query"]);
           for(\$i=0;\$i<count(\$qtypes);\$i++){
             \$w.="{\$qtypes[\$i]} like '%{\$querys[\$i]}%' and "; 
           }
           if(substr(\$w,strlen(\$w)-4,4)=="and ")
           \$w=substr(\$w,0,strlen(\$w)-4); 
           //print_r(\$w);
           return \$w;
            
        }
              //生成json数据
    public function  json(\$action,\$sql,\$P,\$primaryKey)
    {
        
        //以下为模板      
       \$sql0=\$sql." where {where} order by {order} limit {start},{end}";
       \$sql1=\$sql." where {where}";
        \$page=\$P['page'];
        \$rp=\$P['rp'];
        \$sortname=\$P['sortname'];
        \$sortorder=\$P['sortorder'];
        \$qtype=\$P['qtype'];
        \$query=\$P['query'];
        if(!\$sortorder) \$sortorder="asc";
        if(!\$sortname) \$sortname="id";  
        if(!\$page) \$page=1;   
        if(!\$rp ) \$rp =10;
        \$where=\$this->buildWhere(\$P);
        \$order= \$sortname." ".\$sortorder;
        \$start=(\$page-1)*\$rp;
        \$end=\$rp;
        \$sql0=\$this->TemplateReplace("where",\$where,\$sql0);
        \$sql0=\$this->TemplateReplace("order",\$order,\$sql0);
        \$sql0=\$this->TemplateReplace("start",\$start,\$sql0);
        \$sql0=\$this->TemplateReplace("end",\$end,\$sql0);
        \$data=array();
        \$data[0]=\$this->db->query(\$sql0);
        \$data[1]=\$page;
        \$sql1=\$this->TemplateReplace("where",\$where,\$sql1);
        \$data[2]=count(\$this->db->query(\$sql1));
        if(method_exists(\$action,'buildJSON'))
        {
         header("Content-type:text/html;charset=utf-8");   //这句很重要,防止乱码   
         echo \$action->buildJSON(\$data[0],\$primaryKey,\$data[1],\$data[2]);
        }
        return \$data;
    }
}
?>
eot;


$FormValidateTemplate=<<<eot
     // 自动验证设置
     /*
  
     //  array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
     */
    //  验证条件：（可选）   
    // Model::EXISTS_TO_VAILIDATE 或者0 存在字段就验证 （默认）
    //  Model::MUST_TO_VALIDATE 或者1 必须验证 
    //  Model::VALUE_TO_VAILIDATE或者2 值不为空的时候验证
    
    //附加规则： 配合验证规则使用（可选），包括： 
    //regex 使用正则进行验证，表示前面定义的验证规则是一个正则表达式（默认）
    //function 使用函数验证，前面定义的验证规则是一个函数名
    //callback 使用方法验证，前面定义的验证规则是当前Model类的一个方法
    //confirm 验证表单中的两个字段是否相同，前面定义的验证规则是一个字段名
    //equal 验证是否等于某个值，该值由前面的验证规则定义
    //in 验证是否在某个范围内，前面定义的验证规则必须是一个数组
    //unique 验证是否唯一，系统会根据字段目前的值查询数据库来判断是否存在相同的值
    
    //验证时间：（可选）
    //Model:: MODEL_INSERT 或者1新增数据时候验证
    // Model:: MODEL_UPDATE 或者2编辑数据时候验证
    // Model:: MODEL_BOTH 或者3 全部情况下验证（默认）

    
  
    protected \$_validate     =     array(
        {Validate}    
        );
eot;

$FormAutoTemplate=<<<eot

    // 自动填充设置
    //array(填充字段,填充内容,填充条件,附加规则)

    //填充字段就是需要进行处理的表单字段，这个字段不一定是数据库字段，也可以是表单的一些辅助字段，例如确认密码和验证码等等。

    //填充条件包括：

    // Model:: MODEL_INSERT 或者1 新增数据的时候处理（默认）

    // Model:: MODEL_UPDATE 或者2更新数据的时候处理

    // Model:: MODEL_BOTH 或者3所有情况都进行处理

    //附加规则包括：

    // function ：使用函数，表示填充的内容是一个函数名 

    // callback ：回调方法 ，表示填充的内容是一个当前模型的方法

    // field ：用其它字段填充，表示填充的内容是一个其他字段的值

    // string ：字符串（默认方式）

    protected \$_auto     =     array(
        {Auto}
        );
eot;

$FieldMapTemplate=<<<eot
//字段映射
//protected \$_map = array(

    {FieldMap}

//);

eot;

$FlexGridTemplate=<<<eot
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<load href="__PUBLIC__/Js/jquery.js" /> 
<load href='__PUBLIC__/Css/flexigrid.css' />  
<load href='__PUBLIC__/Css/thickbox.css' /> 
<load href="__PUBLIC__/Js/flexigrid.js" /> 
<load href="__PUBLIC__/Js/thickbox.js" />  
 
</head>
<body>
<a id="add" style="display:none" href="__URL__/add/?keepThis=true&TB_iframe=true&height=100%&width=100%" title="新增数据" class="thickbox"></a>  
<a id="edit" style="display:none"  href="__URL__/edit/id/{id}//?keepThis=true&TB_iframe=true&height=100%&width=100%" title="修改数据" class="thickbox"></a>  
<a id="delete" style="display:none"  href="__URL__/delete/id/{id}//?keepThis=true&TB_iframe=true&height=100%&width=100%" title="删除数据" class="thickbox"></a>  
 
<table id="flex1" style="display:none"></table>

<script type="text/javascript">



            $("#flex1").flexigrid
            (
            {
            url: 'json',
            dataType: 'json',
            //searchField对应数据库里的字段,多个字段用逗号隔开,同时可以自定搜索服务端的buildWhere方法,id为查询按钮的id必填,onpress为自定义钮的方法一般为空,name为查询按钮显示给用户我名称
            //filter:{filter:"<div class='fbutton'><span>邮箱<input type='text'/></span><span id='abc'>查询</span></div>",name:'查询',searchField:"email,title,content",onpress:flexCommand,id:'abc'},
            colModel : [
                {FieldColModel}
                ],
            buttons : [
                {name: '增加', bclass: 'add', onpress : flexCommand},
                {name: '删除', bclass: 'delete', onpress : flexCommand},
                {name: '编辑', bclass: 'edit', onpress : flexCommand},
                {separator: true}
                ],
            searchitems : [
                {FieldSearchItems}
                ],
            sortname: "id",
            sortorder: "asc",
            usepager: true,
            title: '{Form}',
            useRp: true,
            rp: 15,
            showTableToggleBtn: true,
            width: 700,
            height: 200,
            pagestat: '显示从 {from} 到 {to} 共 {total} 条记录',
            procmsg: '数据加载中...',
            nomsg: '没找到相关记录.',
            errormsg: '连接出错.'
            }
            );
            
           function flexCommand(com,grid)
            {
              var id="";
              
               for(var i=0;i<$('.trSelected',grid).length;i++)
               {
                   id+=$('.trSelected',grid).get(i).id.substring(3)+",";
               }
                if(id.length>0)id=id.substring(0,id.length-1);
                if (com=='删除')
                    {   
                        //confirm('Delete ' + $('.trSelected',grid).length + ' items?')
                       if( $('.trSelected',grid).length ==0)
                       {
                          alert('请选择要删除的项');
                       }
                       else
                       {
                         var yes=  confirm('确认删除已选中的 ' + $('.trSelected',grid).length + ' 项吗?')
                         {
                           if(yes)
                           {
                             var url="__URL__/delete/id/{id}//?keepThis=true&TB_iframe=true&height=100%&width=100%";
                              $("#delete").attr("href",url.replace(/\{id\}/,id)); 
                              $("#delete").trigger("click") 
                              
                              //tb_remove();
                              //flexReload();
                               
                             
                           }
                         }
                       }
                    }
                else if (com=='增加')
                    {
                       
                      $("#add").trigger("click")
                   
                    } 
                else if (com=='编辑')
                    {
                       if( $('.trSelected',grid).length ==0)
                       {
                          alert('请选择要编辑的项');
                       }
                       else
                       {
                              if( $('.trSelected',grid).length >1)
                              {
                                  alert('请选择其中1项,你已经选择了'+$('.trSelected',grid).length+"项"); 
                              }
                              else
                              {
                                  var url="__URL__/edit/id/{id}//?keepThis=true&TB_iframe=true&height=100%&width=100%";
                                  $("#edit").attr("href",url.replace(/\{id\}/,id)); 
                                  $("#edit").trigger("click") 
                              }

                       }
                    } 
                  else if ("查询"==com)
                    {
                    // debugger;
                   var sValue= $('input[type=text]',$(".tDiv",grid)).eq(0).val();
                        alert(sValue);
                    }            
            }
       /*
        $('b.top').click
        (
            function ()
                {
                    $(this).parent().toggleClass('fh');
                }
        );
         */
            function flexReload()
            {
            $("#flex1").flexReload();
            }  
</script>
</body>
</html>


eot;


$ModelInserSql=<<<eot
        //插入SQL
        public function insertBySql(\$P)
        {
            if(!empty(\$P))
            {
            \$sql="insert into {TableName}({FieldsName})".
            " values({FieldsValue})";            
             return \$this->db->execute(\$sql);
            }
            else
            {
              return false;
            }
        }

eot;

$ModelUpdateSql=<<<eot
          //更新SQL
        public function updateBySql(\$P)
        {
            if(!empty(\$P))
            {
            \$sql="update {TableName} set {UpdateFields} where id='{\$P['id']}'";           
             return \$this->db->execute(\$sql);
            }
            else
            {
              return false;
            }
        }
eot;




?>